﻿using ZYCommon;
using System;
using System.Collections;
using System.Data;
using System.Xml;

namespace TextEditor
{
   

    public class ZYDataSource
    {
        private const string DS_ALL = "all";
        private const string DS_Convert = "convert";
        private const string DS_DataSource = "datasource";
        private const string DS_ErrConn = "错误:未能连接数据库";
        private const string DS_Execute = "execute";
        private const string DS_Exit = "exit";
        private const int DS_ExitFlag = -2;
        private const string DS_FormatTime = "formattime";
        private const string DS_From = "from";
        private const string DS_Get = "get";
        private const string DS_Item = "item";
        private const string DS_List = "list";
        private const string DS_Name = "name";
        private const int DS_Normal = 0;
        private const string DS_One = "one";
        private const string DS_Option = "option";
        private const string DS_Set = "set";
        private const string DS_SetValue = "setvalue";
        private const string DS_SQL = "sql";
        private const string DS_SQLExecute = "sqlexecute";
        private const string DS_SQLParam = "sqlparam";
        private const string DS_SQLQuery = "sqlquery";
        private const string DS_SQLText = "sqltext";
        private const string DS_Text = "text";
        private const string DS_To = "to";
        private const string DS_Type = "type";
        private const string DS_Value = "value";
        private const string DS_ValueEnd = "]";
        private const string DS_ValueHead = "[";
        private IDbCommand myCmd;
        private ZYDBConnection myDBConn = ZYDBConnection.Instance;
        private XmlDocument myDefineXML = null;
        private ArrayList myQueryNames = new ArrayList();
        private NameValueList myQueryVariables = new NameValueList();
        private Hashtable myVariables = new Hashtable();

        public void AddQueryName(string strName)
        {
            if ((strName != null) && (strName.Trim().Length > 0))
            {
                strName = strName.Trim();
                foreach (string str in this.myQueryNames)
                {
                    if (str.Equals(strName))
                    {
                        return;
                    }
                }
                this.myQueryNames.Add(strName);
            }
        }

        public void AddQueryVariable(string strName, string strValue)
        {
            this.myQueryVariables.SetValue(strName, strValue);
        }

        public void AddQueryVariablesByXML(XmlElement RootElement)
        {
            if (RootElement != null)
            {
                foreach (XmlNode node in RootElement.ChildNodes)
                {
                    XmlElement element = node as XmlElement;
                    if (element != null)
                    {
                        this.myQueryVariables.SetValue(element.GetAttribute("name"), element.InnerText);
                    }
                }
            }
        }

        public void ClearQueryNames()
        {
            this.myQueryNames.Clear();
        }

        public void ClearQueryVariables()
        {
            this.myQueryVariables.Clear();
        }

        public void executeDataSource(XmlElement myXMLElement)
        {
            try
            {
                ArrayList list = new ArrayList();
                XmlNodeList childNodes = myXMLElement.ChildNodes;
                for (int i = 0; i < childNodes.Count; i++)
                {
                    if (i > (childNodes.Count - 1))
                    {
                        i = childNodes.Count - 1;
                    }
                    if (childNodes[i] is XmlElement)
                    {
                        XmlElement oldChild = (XmlElement) childNodes[i];
                        try
                        {
                            string name = oldChild.Name;
                            if (name.Equals("setvalue"))
                            {
                                this.myVariables[oldChild.GetAttribute("name")] = oldChild.InnerText;
                            }
                            else if (name.Equals("datasource"))
                            {
                                string attribute = oldChild.GetAttribute("name");
                                bool flag = false;
                                foreach (string str3 in list)
                                {
                                    if (str3.Equals(attribute))
                                    {
                                        flag = true;
                                        break;
                                    }
                                }
                                if (flag)
                                {
                                    myXMLElement.RemoveChild(oldChild);
                                    i--;
                                }
                                else
                                {
                                    list.Add(attribute);
                                    XmlElement defineElement = XMLCommon.GetElementByName(XMLCommon.GetElementByName(this.myDefineXML.DocumentElement, attribute, true), "get", false);
                                    if (this.runDataSourceElement(oldChild, defineElement) == -2)
                                    {
                                        return;
                                    }
                                }
                            }
                        }
                        catch (Exception exception)
                        {
                            oldChild.InnerText = exception.ToString();
                        }
                    }
                }
            }
            catch
            {
            }
        }

        public XmlDocument ExecuteQuery()
        {
            XmlDocument document = new XmlDocument();
            XmlElement newChild = null;
            document.LoadXml("<datasources />");
            for (int i = 0; i < this.myQueryVariables.Count; i++)
            {
                newChild = document.CreateElement("setvalue");
                newChild.SetAttribute("name", this.myQueryVariables.GetName(i));
                newChild.InnerText = this.myQueryVariables.GetValue(i);
                document.DocumentElement.AppendChild(newChild);
            }
            foreach (string str in this.myQueryNames)
            {
                newChild = document.CreateElement("datasource");
                newChild.SetAttribute("name", str);
                document.DocumentElement.AppendChild(newChild);
            }
            this.executeDataSource(document.DocumentElement);
            return document;
        }

        public string fixVariableString(string strText)
        {
            return StringCommon.fixVariableString(strText, "[", "]", this.myVariables);
        }

        public void LoadDataSourceDefine(string strDefineFile)
        {
        }

        public void RemoveQueryVariable(string strName)
        {
            this.myQueryVariables.Remove(strName);
        }

        public int runDataSourceElement(XmlElement sourceElement, XmlElement defineElement)
        {
            if ((sourceElement != null) && (defineElement != null))
            {
                foreach (XmlNode node in defineElement.ChildNodes)
                {
                    if (!(node is XmlElement))
                    {
                        continue;
                    }
                    XmlElement element = (XmlElement) node;
                    string name = element.Name;
                    if (name.Equals("sql"))
                    {
                        if (!this.myDBConn.isOpened())
                        {
                            return -2;
                        }
                        if (this.runDataSourceElement(sourceElement, element) == -2)
                        {
                            return -2;
                        }
                        continue;
                    }
                    if (name.Equals("sqltext"))
                    {
                        this.myCmd = this.myDBConn.CreateCommand();
                        this.myCmd.CommandText = this.fixVariableString(element.InnerText);
                        continue;
                    }
                    if (name.Equals("sqlparam"))
                    {
                        ZYDBConnection.AddParameter(this.myCmd, this.myVariables[element.GetAttribute("name")]);
                        continue;
                    }
                    if (name.Equals("sqlquery"))
                    {
                        IDataReader myReader = this.myCmd.ExecuteReader();
                        XmlElement newChild = null;
                        int fieldCount = myReader.FieldCount;
                        string attribute = null;
                        attribute = element.GetAttribute("type");
                        if (attribute == null)
                        {
                            attribute = "list";
                        }
                        if (attribute.Equals("list"))
                        {
                            while (myReader.Read())
                            {
                                newChild = sourceElement.OwnerDocument.CreateElement("option");
                                sourceElement.AppendChild(newChild);
                                newChild.SetAttribute("value", myReader.IsDBNull(0) ? "" : myReader[0].ToString());
                                if (myReader.FieldCount == 1)
                                {
                                    newChild.InnerText = myReader.IsDBNull(0) ? "" : myReader[0].ToString();
                                }
                                else
                                {
                                    newChild.InnerText = myReader.IsDBNull(1) ? "" : myReader[1].ToString();
                                }
                            }
                        }
                        else if (attribute.Equals("text"))
                        {
                            if (myReader.Read())
                            {
                                sourceElement.InnerText = myReader.IsDBNull(0) ? "" : myReader[0].ToString();
                            }
                        }
                        else if (attribute.Equals("all"))
                        {
                            this.saveResultSetToXML(sourceElement, myReader, null, false, false);
                        }
                        myReader.Close();
                        this.myCmd.Dispose();
                        this.myCmd = null;
                        continue;
                    }
                    if (name.Equals("convert"))
                    {
                        string str3 = element.GetAttribute("from");
                        string str4 = element.GetAttribute("to");
                        string innerText = sourceElement.InnerText;
                        if (str3 == null)
                        {
                            str3 = "";
                        }
                        if (str4 == null)
                        {
                            str4 = "";
                        }
                        if (innerText == null)
                        {
                            innerText = "";
                        }
                        if (innerText.Trim().Equals(str3))
                        {
                            XMLCommon.ClearChildNode(sourceElement);
                            sourceElement.InnerText = str4;
                        }
                        continue;
                    }
                    if (name.Equals("value"))
                    {
                        XMLCommon.ClearChildNode(sourceElement);
                        sourceElement.InnerText = this.fixVariableString(element.InnerText);
                        continue;
                    }
                    if (name.Equals("item"))
                    {
                        string str6 = element.InnerText;
                        XmlElement element3 = sourceElement.OwnerDocument.CreateElement("option");
                        sourceElement.AppendChild(element3);
                        element3.SetAttribute("value", element.HasAttribute("value") ? element.GetAttribute("value") : str6);
                        element3.InnerText = str6;
                        continue;
                    }
                    if (name.Equals("formattime"))
                    {
                        string strFromFormat = element.GetAttribute("from");
                        string strToFormat = element.GetAttribute("to");
                        string strValue = sourceElement.InnerText;
                        if (strFromFormat == null)
                        {
                            strFromFormat = "";
                        }
                        if (strToFormat == null)
                        {
                            strToFormat = "";
                        }
                        if (strValue == null)
                        {
                            strValue = "";
                        }
                        if ((strToFormat.Length > 0) && (strValue.Length > 0))
                        {
                            sourceElement.InnerText = StringCommon.FormatDateTime(strValue, strFromFormat, strToFormat);
                        }
                        continue;
                    }
                    if (name.Equals("exit"))
                    {
                        return -2;
                    }
                }
            }
            return 0;
        }

        public void SaveQueryVariablesToXML(XmlElement RootElement)
        {
            if (RootElement != null)
            {
                for (int i = 0; i < this.myQueryVariables.Count; i++)
                {
                    XmlElement newChild = RootElement.OwnerDocument.CreateElement("value");
                    newChild.SetAttribute("name", this.myQueryVariables.GetName(i));
                    newChild.InnerText = this.myQueryVariables.GetValue(i);
                    RootElement.AppendChild(newChild);
                }
            }
        }

        public int saveResultSetToXML(XmlElement rootElement, IDataReader myReader, string strRecordName, bool bolOneRecord, bool bolSaveToAttribute)
        {
            if ((rootElement == null) || (myReader == null))
            {
                return -1;
            }
            XmlDocument ownerDocument = rootElement.OwnerDocument;
            int num = 0;
            if (!bolOneRecord)
            {
                if ((strRecordName == null) || (strRecordName.Trim().Length == 0))
                {
                    strRecordName = "record";
                }
                strRecordName = strRecordName.Trim();
            }
            while (myReader.Read())
            {
                XmlElement element;
                num++;
                if (bolOneRecord)
                {
                    element = rootElement;
                }
                else
                {
                    element = ownerDocument.CreateElement(strRecordName);
                    rootElement.AppendChild(element);
                }
                for (int i = 0; i < myReader.FieldCount; i++)
                {
                    string str = myReader.IsDBNull(i) ? "" : myReader[i].ToString();
                    if (bolSaveToAttribute)
                    {
                        element.SetAttribute(myReader.GetName(i).ToLower(), str);
                    }
                    else
                    {
                        XmlElement newChild = ownerDocument.CreateElement(myReader.GetName(i).ToLower());
                        element.AppendChild(newChild);
                        newChild.InnerText = str;
                    }
                }
                if (bolOneRecord)
                {
                    return num;
                }
            }
            return num;
        }

        public ZYDBConnection DBConn
        {
            get
            {
                return this.myDBConn;
            }
            set
            {
                this.myDBConn = value;
            }
        }
    }
}

